#! python
#! coding: utf-8

__author__ = 'Anton Vakhrushev'


from peewee import *


database = SqliteDatabase(None)


class BaseModel(Model):
    class Meta:
        database = database


class Photo(BaseModel):
    sid = CharField(unique=True)
    remote = BooleanField()
    viewed = DateTimeField()
    modified = DateTimeField()
    width = IntegerField(default=0)
    height = IntegerField(default=0)
    ratio = FloatField(null=True)


class Image(BaseModel):
    photo = ForeignKeyField(Photo, related_name='images', on_delete='cascade', on_update='cascade')
    link = CharField(max_length=1024, unique=True)
    data = BlobField()
    viewed = DateTimeField()


class HashValue(BaseModel):
    photo = ForeignKeyField(Photo, related_name='hash_values', on_delete='cascade', on_update='cascade')
    sort = IntegerField()
    value = FloatField()


def close():
    """
    Если база данных была открыта, то закрывает ее
    """
    if not database.is_closed():
        database.close()


def connect(dbname=':memory:'):
    """
    Соединиться с базой данных
    @param dbname: имя базы данных
    @return: база днных
    """
    close()
    database.init(dbname)
    database.connect()
    database.create_tables([Photo, Image, HashValue], safe=True)
    return database


def transaction():
    return database.transaction()


if __name__ == '__main__':
    connect('test.db')
    close()
